import { useParams } from 'react-router-dom'
import { getQuestionService } from '../services/question'
import { useRequest } from 'ahooks'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { resetComponents } from '../store/componentsReducer'
import { resetPageInfo } from '../store/pageInfoReducer'

function useLoadQuestionData() {
  const { id = '' } = useParams()
  const dispatch = useDispatch()
  // const
  //ajax  加载
  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error('没有问卷 id')
      return await getQuestionService(id)
    },
    { manual: true }
  )

  // 根据获取 data,设置 redux store
  useEffect(() => {
    if (!data) return

    const { title = '', desc, js, css, componentList = [], isPublished = false } = data

    // 获取默认的 selectedId
    let selectedId = ''
    if (componentList.length) {
      selectedId = componentList[0].fe_id
    }

    // 把 componentList 存储到 store 中
    dispatch(
      resetComponents({
        componentList,
        selectedId,
        copiedComponent: null,
      })
    )

    // 把 page info 存储到 store 中
    dispatch(
      resetPageInfo({
        title,
        desc,
        js,
        css,
        isPublished,
      })
    )
  }, [data])

  // 根据 id 变化,执行 ajax 加载问卷数据
  useEffect(() => {
    run(id)
  }, [id])

  return { loading, error }
}

export default useLoadQuestionData
